package com.ruoyi.system.service.Impl;


import com.ruoyi.system.domain.imgBrowse;
import com.ruoyi.system.mapper.ImgBrowseMapper;
import com.ruoyi.system.service.ImgBrowseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import javax.xml.bind.DatatypeConverter;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.List;

@Service
@Transactional
public class ImgBrowseServiceImpl implements ImgBrowseService {

    @Autowired(required = false)
    private ImgBrowseMapper imgBrowseMapper;

    @Override
    public List<imgBrowse> findUploadImagePathByUserId(String userId) {
        return imgBrowseMapper.findUploadImagePathByUserId(userId);
    }

    @Override
    public imgBrowse findUploadImagePathByImageId(String upId) {
        return imgBrowseMapper.findUploadImagePathByImageId(upId);
    }

    @Override
    public void byteArrayToFile(byte[] src, String filePath) {
        //1.创建源
        File file = new File(filePath);
        //选择流
        InputStream writing = null;
        OutputStream os = null;
        try {
            writing = new ByteArrayInputStream(src);
            os = new FileOutputStream(file);
            byte[] frush = new byte[5];//3表示0个字节为一段
            int len = -1;
            while ((len = writing.read(frush)) != -1) {
                os.write(frush, 0, len);
            }
            os.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }


    public String base64Image(String path) throws IOException {
        String imageString;
        int width;
        int height;
        File file = new File("D:" + path);
        Image src = ImageIO.read(file);
        width = src.getWidth(null);
        height = src.getHeight(null);
        //设置图片流
        BufferedImage tag = new BufferedImage(width / 2, height / 2, BufferedImage.TYPE_INT_RGB);
        //绘制缩小后的图
        tag.getGraphics().drawImage(src, 0, 0, width / 2, height / 2, null);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(tag, "png", baos);

        String data = DatatypeConverter.printBase64Binary(baos.toByteArray());
        imageString = "data:image/png;base64," + data;

        return imageString;
    }

}
